<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>caesarCipher</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            height: 100vh;
            background-color: #f0f4f7;
        }

        .container {
            text-align: center;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 400px;
        }

        input,
        button {
            padding: 10px;
            margin: 10px;
            width: 80%;
            font-size: 16px;
        }

        .result {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <p>
        <strong>凯撒密码</strong>（Caesar Cipher）的加密和解密功能。凯撒密码是一种简单的字母替换加密方式，将字母通过固定的偏移量进行转换。
    </p>
    <div class="container">
        <h2>凯撒密码加密/解密</h2>
        <input type="text" id="inputText" placeholder="输入文本" />
        <input type="number" id="shift" placeholder="输入偏移量" />
        <button onclick="processCipher(false)">加密</button>
        <button onclick="processCipher(true)">解密</button>
        <div class="result" id="result"></div>
    </div>

    <script>
        const caesarCipher = (str, shift, decrypt = false) => {
            const s = decrypt ? (26 - shift) % 26 : shift;
            const n = s > 0 ? s : 26 + (s % 26);
            return [...str]
                .map((l) => {
                    const c = l.charCodeAt(0);
                    // 处理大写字母
                    if (c >= 65 && c <= 90)
                        return String.fromCharCode(((c - 65 + n) % 26) + 65);
                    if (c >= 97 && c <= 122)
                        return String.fromCharCode(((c - 97 + n) % 26) + 97);
                    return l;
                })
                .join('');
        };

        function processCipher(decrypt) {
            const text = document.getElementById('inputText').value;
            const shift = parseInt(document.getElementById('shift').value);

            if (text && !isNaN(shift)) {
                const result = caesarCipher(text, shift, decrypt);
                document.getElementById('result').textContent = `结果: ${result}`;
            } else {
                alert("请输入有效的文本和偏移量！");
            }
        }
    </script>

</body>

</html>